const { success, failure } = require("../../utils/responses");
const coursesService = require("../../services/learn/coursesService");

/**
 * 课程列表
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.list = async (req, res) => {
  try {
    // 分页查询
    const { count, rows, currentPage, pageSize } =
      await coursesService.list(req);
    // 返回
    success(res, "课程查询成功", {
      lists: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 添加课程
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.add = async (req, res) => {
  try {
    const body = this.filterBody(req);
    // 获取当前用户Id
    body.userId = req.user.id;
    const course = await coursesService.create(body);
    success(res, "创建课程成功", course, 201);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 删除课程
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.del = async (req, res) => {
  try {
    await coursesService.del(req.body.id || req.params.id || req.query.id);
    success(res, "删除课程成功");
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 更新课程
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.update = async (req, res) => {
  try {
    const body = this.filterBody(req);
    const course = await coursesService.update(req.body.id, body);
    success(res, "更新课程成功", course);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 课程详情
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.details = async (req, res) => {
  try {
    const course = await coursesService.details(
      req.body.id || req.params.id || req.query.id,
    );
    success(res, "查询课程成功", course);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 过滤body
 * @param req
 * @returns {{image: *, name, introductory: (boolean|*), userId, categoryId: (number|*), content, recommended: (boolean|*)}}
 */
exports.filterBody = (req) => {
  return {
    categoryId: req.body.categoryId,
    userId: req.body.userId,
    name: req.body.name,
    image: req.body.image,
    recommended: req.body.recommended,
    introductory: req.body.introductory,
    content: req.body.content,
  };
};
